package blog.dao;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import blog.domain.User;

@Transactional(propagation = Propagation.MANDATORY)
public class UserDao {
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Transactional(propagation = Propagation.SUPPORTS)
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public User getUser(String username) {
		Query query = sessionFactory.getCurrentSession()
				.createQuery("from User u where u.name = :username");
		query.setParameter("username", username);
		 return (User)query.uniqueResult();
	}

	public boolean validateUser(String username, String password) {
		Query query = sessionFactory.getCurrentSession()
				.createQuery(
						" from User u where u.name = :username and u.password = :password");
		query.setParameter("username", username);
		query.setParameter("password", password);
		Object user = query.uniqueResult();
		if (user != null) {
			return true;
		}
		return false;
	}

}
